<?php
/**
 * Created by PhpStorm.
 * User: 2233
 * Date: 2021/4/3
 * Time: 22:56
 */
namespace app\lib\exception\base;
use think\exception\Handle;
use think\facade\Log;
use think\facade\Request;

class ExceptionHandel extends Handle
{
    // 状态码
    private $code;
    // 错误信息
    private $msg;
    // 自定义错误状态码
    private $errorCode;

    public function render(\Exception $e){
        if ($e instanceof BaseException){
            Log::close();
            $this->code = $e->getCode();
            $this->msg = $e->getMsg();
            $this->errorCode = $e->getErrorCode();
        }else{
            //开启调试模式
           if (config('app_debug')){
               return parent::render($e);
           }
            $this->code = 500;
            $this->msg =  '服务器内部错误';
            $this->errorCode = 999;
            //写入日志
           $this->renderErrorLog($e);
        }
        //发生错误控路径
        $request = Request::url();
        $result = [
            'msg' => $this->msg,
            'errorCode' => $this->errorCode,
            'request_url' => $request,
        ];
        return json($result,$this->code);
    }


    /**
     * 错误写入数据库和写入文件中
     * @param \Exception $e
     */
    private function renderErrorLog(\Exception $e){
        $msg = $e->getMessage();
        Log::error($msg);
    }
}